package org.snake.demo.mvc.action;

import org.snake.demo.service.IModifyService;
import org.snake.demo.service.IQueryService;
import org.snake.mvcframework.annotation.RAYAutowired;
import org.snake.mvcframework.annotation.RAYController;
import org.snake.mvcframework.annotation.RAYRequestMapping;
import org.snake.mvcframework.annotation.RAYRequestParam;
import org.snake.spring.framework.webmvc.servlet.RAYModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 公布接口url
 *
 * @author Ray
 */
@RAYController
@RAYRequestMapping("/web")
public class MyAction
{

    @RAYAutowired
    IQueryService queryService;

    @RAYAutowired
    IModifyService modifyService;

    @RAYRequestMapping("/query.json")
    public RAYModelAndView query(HttpServletRequest request, HttpServletResponse response, @RAYRequestParam("name") String name)
    {

        String result = queryService.query(name);
        return out(response, result);
    }

    @RAYRequestMapping("/add*.json")
    public RAYModelAndView add(HttpServletRequest request, HttpServletResponse response, @RAYRequestParam("name") String name, @RAYRequestParam("addr") String addr)
    {

//        String result = modifyService.add(name, addr);
//        return out(response, result);

        String result = null;
        try {
            result = modifyService.add(name,addr);
        } catch (Exception e) {
            Map<String,Object> model = new HashMap<String, Object>();
            model.put("detail","500 Exception Detail," + e.getCause().getMessage());
            model.put("stackTrace", Arrays.toString(e.getStackTrace()));
            return new RAYModelAndView("500",model);
        }

        return out(response,result);
    }

    @RAYRequestMapping("/remove.json")
    public RAYModelAndView remove(HttpServletRequest request, HttpServletResponse response, @RAYRequestParam("id") Integer id)
    {

        String result = modifyService.remove(id);
        return out(response, result);
    }

    @RAYRequestMapping("/calc.json")
    public RAYModelAndView remove(HttpServletResponse response, @RAYRequestParam("a") Integer a, @RAYRequestParam("b") Integer b)
    {

        String result = modifyService.calc(a, b);
        return out(response, result);
    }

    @RAYRequestMapping("/edit.json")
    public RAYModelAndView edit(HttpServletRequest request, HttpServletResponse response, @RAYRequestParam("id") Integer id, @RAYRequestParam("name") String name)
    {

        String result = modifyService.edit(id, name);
        return out(response, result);
    }

    private RAYModelAndView out(HttpServletResponse resp, String str)
    {

        try
        {
            resp.getWriter().write(str);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

}
